<?php


namespace App\Service\OpenShop\Feishu;

use App\Enums\OpenShop\User\CodeEnum;
use App\Exceptions\Custom\CustomException;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Models\Common\FsCompanyUserModel;
use App\Models\Feishu\FsLoginLogModel;
use GuzzleHttp\Exception\GuzzleException;

class LoginService
{
    const RMS_LOGIN_URL = 'api/internal/openShop/login';

    public static function login($code, string $webPlatform, string $appid, string $ip)
    {
        //获取飞书用户信息
        $userInfo = BaseService::getUserInfo($code, $webPlatform, $appid);
        $mobile   = substr($userInfo['data']['mobile'] ?? '', -11);

        // 更新fs_company_users
        $userInfoCode = $userInfo['code'] ?? -1;

        // 判断接口是否开通权限
        if (empty($userInfo['data']['user_id'])) {
            throw new CustomException('检查是否开通飞书应用权限: "contact:user.id:readonly", 以及"contact:user.employee_id:readonly" 权限');
        }

        if ($appid && $userInfoCode == 0) {

            $data            = [
                'name'    => $userInfo['data']['name'] ?? '',
                'phone'   => $mobile,
                'openId'  => $userInfo['data']['open_id'] ?? '',
                'unionId' => $userInfo['data']['union_id'] ?? '',
                'avatar'  => $userInfo['data']['avatar_url'] ?? '',
            ];
            $fsCompanyUserId = FsCompanyUserModel::add($appid, $userInfo['data']['user_id'], $data)->id;
        }

        //调用rms用户基本信息
        $rms = self::doLogin($mobile, $userInfo['data']['user_id'], true, $ip);

        $rmsUserId = $rms['userInfo']['id'] ?? null;

        // 更新fs_company_users.rmsUserId
        if (isset($fsCompanyUserId)) {
            FsCompanyUserModel::saveRmsUserId($fsCompanyUserId, $rms['userInfo']['id'] ?? null);
        }

        // 记录登录日志
        FsLoginLogModel::add((int)$rmsUserId, $userInfo['data']['userId'] ?? '', $appid, $webPlatform);

        return $rms;
    }

    /**
     * @param $mobile
     * @param $openId
     * @param $userId
     * @return mixed
     * @throws GuzzleException
     */
    public static function doLogin($mobile, $userId, bool $throw = true, string $ip = '')
    {
        $url      = config('rms.domain') . self::RMS_LOGIN_URL;
        $body     = ['mobile' => $mobile, 'userId' => $userId, 'ip' => $ip];
        $header   = ['internal-key' => config('rms.internalKey'), 'internal-token' => config('rms.internalValue')];
        $response = getRmsMessageCommon("POST", $url, $body, $header, 'json');

        // 不报错
        if (!$throw) {
            return $response['data'] ?? [];
        }

        if ($response['code'] != 200) {
            throw new CustomHttpResponseException($response['code'], null, $response['msg']);
        }
        if ((isset($response['data']['userInfo']) && $response['data']['userInfo']['status'] != CodeEnum::USER_STATUS_IS_NORMAL)) {
            throw new CustomHttpResponseException(CodeEnum::errCodeTrans(CodeEnum::USER_STATUS_IS_ERROR));
        }
        return $response['data'];
    }
}
